package com.rongshu.view.penpal.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.home.activity.SingleArticleDetailsActivity;
import com.rongshu.view.penpal.activity.PostDetailsActivity;
import com.rongshu.view.penpal.adapter.PenpalArticleListManagerAdapter;
import com.rongshu.view.penpal.bean.PenpalArticleResponse;
import com.rongshu.view.penpal.present.PenpalArticleManagerPresenter;
import com.rongshu.view.penpal.view.ArticleAdapterListener;
import com.rongshu.view.penpal.view.PenpalArticleManagerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * created by zhengweis on 2018/11/22.
 * description：笔友会文章/帖子管理
 */
public class Penpal_ArticleManagerFragment extends BaseFragment<PenpalArticleManagerPresenter> implements PenpalArticleManagerView {
    @BindView(R.id.article_list)
    RecyclerView articleList;
    @BindView(R.id.refresh_view)
    SmartRefreshLayout refreshView;
    @BindView(R.id.no_data_img)
    ImageView noData;
    @BindView(R.id.no_data_hint)
    TextView noDataHint;
    private int penpalwill_id;
    private int type;
    private int pageIndex = 1;
    private int pageSize = 10;
    private List<PenpalArticleResponse.ResponseBean> articles;
    private PenpalArticleListManagerAdapter articleAdapter;
    private int deleteArticlePosition;
    private int setTopArticlePosition;
    private int pushPiazza;
    private int itemClickPosition;
    private int INTENT_DETAILS_REQUEST = 1001;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_penpal_article_list;
    }

    @Override
    protected void initViews() {
        refreshView.setEnableAutoLoadmore(false);
        Bundle bundle = getArguments();
        if (bundle != null) {
            penpalwill_id = bundle.getInt("penpalwill_id");
            type = bundle.getInt("type");
        }
        noData.setBackgroundResource(type == Constant.ARTICLE ? R.drawable.empty_article : R.drawable.empty_post);
        noDataHint.setText(type == Constant.ARTICLE ? "还没有文章哦" : "还没有帖子哦");
    }

    @Override
    protected void initData() {
        setPresenter(new PenpalArticleManagerPresenter(getActivity()), this);
        presenter.getPenpalArticles(penpalwill_id, type, pageIndex, pageSize);

        articles = new ArrayList<>();
        LinearLayoutManager articleManager = new LinearLayoutManager(getActivity());
        articleList.setLayoutManager(articleManager);
        articleAdapter = new PenpalArticleListManagerAdapter(getActivity(), articles, type);
        articleList.setAdapter(articleAdapter);
        articleAdapter.setAdapter(new ArticleAdapterListener() {
            @Override
            public void onDeleteListener(int position) {
                deleteArticlePosition = position;
                presenter.deleteArticle(penpalwill_id, articles.get(position).getTopic_id());
            }

            @Override
            public void onSetTopListener(int position) {
                setTopArticlePosition = position;
                presenter.setTopArticle(penpalwill_id, articles.get(position).getTopic_id());
            }

            @Override
            public void pushPiazza(int position) {
                pushPiazza = position;
                int pushType;
                if (articles.get(position).getIsPlaza() == 0) {
                    pushType = 1;
                } else {
                    pushType = 2;
                }
                presenter.pushPiazza(articles.get(position).getTopic_id(), penpalwill_id, pushType);
            }

            @Override
            public void onItemClickListener(int position) {
                itemClickPosition = position;
                if (type == Constant.ARTICLE) {
                    Intent intent = new Intent(getActivity(), SingleArticleDetailsActivity.class);
                    ArticleDetaisRequest request = new ArticleDetaisRequest();
                    request.setTopic_id(articles.get(position).getTopic_id());
                    request.setType(3);
                    request.setContribute_id(articles.get(position).getContribute_id());
                    intent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, request);
                    startActivityForResult(intent, INTENT_DETAILS_REQUEST);
                } else {
                    Intent intent = new Intent(getActivity(), PostDetailsActivity.class);
                    intent.putExtra(Constant.POST_ID, articles.get(position).getTopic_id());
                    intent.putExtra("showJoinIcon", true);
                    startActivityForResult(intent, INTENT_DETAILS_REQUEST);
                }
            }
        });

        refreshView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageIndex = 1;
                refreshlayout.resetNoMoreData();
                presenter.getPenpalArticles(penpalwill_id, type, pageIndex, pageSize);
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshView.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                presenter.getPenpalArticles(penpalwill_id, type, pageIndex, pageSize);
                refreshlayout.finishLoadmore(2000/*,false*/);//传入false表示刷新失败
            }
        });
    }

    @Override
    protected void updateViews(boolean isRefresh) {
    }

    @Override
    public void callBackArticleList(PenpalArticleResponse response) {
        if (pageIndex == 1) {
            articles.clear();
        }
        if (refreshView.isRefreshing()) {
            refreshView.finishRefresh();
        }
        if (refreshView.isLoading()) {
            refreshView.finishLoadmore();
        }
        if (response != null && response.getResponse() != null) {
            articles.addAll(response.getResponse());
            articleAdapter.notifyDataSetChanged();
            contentIsEmpty(articles.size() == 0);
            if (response.getResponse().size() == 0) {
                refreshView.setLoadmoreFinished(true);
            }
        }
    }

    @Override
    public void callBackSetTopResult() {
        /**
         * TODO: 2018/11/27 执行置顶操作，刷新列表方式：
         * 1、暂时改变本地数据并刷新列表，不去请求接口；该方式导致被置顶的item不能马上移动到顶部
         * 2、重新请求接口，获取最新数据并刷新列表；该方式导致列表将重新回到顶部第一条item，且展示第一页内容
         * 暂时使用方案1
         */
        if (articles.get(setTopArticlePosition).getIstop() == 0) {
            articles.get(setTopArticlePosition).setIstop(1);
        } else {
            articles.get(setTopArticlePosition).setIstop(0);
        }
        articleAdapter.notifyDataSetChanged();
    }

    @Override
    public void callBackDeleteResult() {
        articles.remove(deleteArticlePosition);
        articleAdapter.notifyDataSetChanged();
        contentIsEmpty(articles.size() == 0);
    }

    @Override
    public void callBackPushPiazzaResult() {
        if (articles.get(pushPiazza).getIsPlaza() == 0) {
            articles.get(pushPiazza).setIsPlaza(1);
        } else {
            articles.get(pushPiazza).setIsPlaza(0);
        }
        articleAdapter.notifyDataSetChanged();
    }

    private void contentIsEmpty(boolean isEmpty){
        noData.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
        noDataHint.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == INTENT_DETAILS_REQUEST){
            int likeCount = data.getIntExtra(Constant.LIKE_COUNT,0);
            int commentCount = data.getIntExtra(Constant.COMMENT_COUNT,0);
            articles.get(itemClickPosition).setLikeCount(likeCount);
            articles.get(itemClickPosition).setCommentCount(commentCount);
            articleAdapter.notifyItemChanged(itemClickPosition);
        }
    }
}
